package monsterRun.client.view;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.rmi.RemoteException;

import javax.swing.*;

import Testing.PlayerMessagesInterface;

import monsterRun.client.model.Facade;
import monsterRun.client.view.renderer.RendererPanel;
import monsterRun.client.view.renderer.themes.AbstractBoardTheme;
import monsterRun.client.view.renderer.themes.BlueBoardTheme;
import monsterRun.client.view.renderer.themes.DarkBoardTheme;
import monsterRun.client.view.renderer.themes.DefaultBoardTheme;
import monsterRun.client.view.renderer.themes.GreenBoardTheme;
import monsterRun.client.view.renderer.themes.LightBoardTheme;
import monsterRun.client.view.renderer.themes.RedBoardTheme;
import monsterRun.common.model.ImageStore;
import monsterRun.common.model.MessageFactory;
import monsterRun.common.model.enums.MessageID;
import monsterRun.common.model.network.NetworkMessage;
import monsterRun.common.model.network.events.IMessageReceivedListener;
import monsterRun.common.view.MToolbar;
import monsterRun.common.view.Preference;

public class Toolbar extends MToolbar implements IMessageReceivedListener
{
	private static final long serialVersionUID = 6512066561214373329L;

	private JButton newGameButton;
	private JComboBox themeSwitcher;
	private JButton fullScreenButton;

	private JLabel uNameLabel;
	private JTextField uName;

	private JLabel pWordLabel;
	private JPasswordField pWord;

	private JButton loginButton;
	private JButton registerButton;
	
	private JLabel userNameLogged;

	private AbstractBoardTheme themes[];

	public Toolbar(final MonsterFrame frame, final Facade facade,
			final RendererPanel renderer)
	{

		super(renderer, Preference.HEADER_BACKGROUND,
				Preference.HEADER_BACKGROUND_DARK);

		// New Game
		newGameButton = new JButton("Join Game");
		newGameButton.setOpaque(false);
		//setting button to true for testing purpose
		newGameButton.setEnabled(false);
		newGameButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				// newGameButton.setEnabled(false);

				frame.showWaitingPanel();

				// facade.getCommunicator().sendMessage(
				// MessageFactory.createJoinGameRequest());
				PlayerMessagesInterface pmi = facade
				.getPlayerMessagesInterface();
				try
				{
					// pmi.createJoinGameRequest();
					frame.joinGame();

				}
				catch (RemoteException e1)
				{
					e1.printStackTrace();
				}
			}
		});

		add(newGameButton);

		// Theme switcher
		themes = new AbstractBoardTheme[] { new DefaultBoardTheme(),
				new BlueBoardTheme(), new DarkBoardTheme(),
				new LightBoardTheme(), new GreenBoardTheme(),
				new RedBoardTheme() };

		themeSwitcher = new JComboBox(themes);
		themeSwitcher.setOpaque(false);
		themeSwitcher.setFocusable(false);
		themeSwitcher.addItemListener(new ItemListener()
		{
			@Override
			public void itemStateChanged(ItemEvent e)
			{
				facade.setTheme((AbstractBoardTheme) themeSwitcher
						.getSelectedItem());
			}
		});

		add(themeSwitcher);

		// Full screen
		fullScreenButton = new JButton(ImageStore.get().getIcon(
		"fullscreen.png"));
		fullScreenButton.setOpaque(false);
		fullScreenButton.setToolTipText("Enter/Exit Fullscreen mode");
		fullScreenButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				Preference.setFullscreen(!Preference.isFullscreen());
			}
		});

		add(fullScreenButton);

		/**	@author s3252820 Gareth Ng 2012
		 *  Added the JLabels and JTextFields for username and password
		 *  for logging in as well as the Registration Button.
		 *  
		 */

		uNameLabel = new JLabel("Username: ");
		uNameLabel.setOpaque(false);

		add(uNameLabel);

		uName = new JTextField(5);
		uName.setBackground(Color.WHITE);

		add(uName);
		
		userNameLogged = new JLabel();
		userNameLogged.setVisible(false);
		
		add(userNameLogged);

		pWordLabel = new JLabel("Password: ");
		pWordLabel.setOpaque(false);

		add(pWordLabel);

		pWord = new JPasswordField(5);
		pWord.setBackground(Color.WHITE);

		add(pWord);

		loginButton = new JButton("Login");
		loginButton.setOpaque(false);

		loginButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				// loginButton.setEnabled(false);

				String str = "";
				char[] c = pWord.getPassword();
				for (int i= 0 ; i < c.length; i++){
					str = str + c[i];
				}

				/** loginButton will check once clicked if there is a username and
				 *  password field entered, if not return a JOptionPane error mesage
				 *  
				 *  It will then check the if the user and password are in the database
				 *  using a method in the server which will check the database through the
				 *  data access layer. If not, it will return false which will open a 
				 *  JOptionPane error message
				 *  
				 * @author s3252820 Gareth Ng 2012
				 */
				if (uName.getText().trim().compareTo("")==0 && str.trim().compareTo("")==0){
					JOptionPane.showMessageDialog(frame,
							"Please enter username and password to log in",
							"Login Error",
							JOptionPane.ERROR_MESSAGE);
				} else{
					frame.showWaitingPanel();

					PlayerMessagesInterface pmi = facade
					.getPlayerMessagesInterface();
					try
					{
						String[] s = { uName.getText(), str };
						if (!pmi.sendLoginDetails(s))
						{
							frame.hidePopups();
							JOptionPane.showMessageDialog(frame,
									"Invalid User/Password Combination.\nTry Again!",
									"Login Error",
									JOptionPane.ERROR_MESSAGE);
						}
						else
						{
							JOptionPane.showMessageDialog(frame,
									"Welcome to the game, "+uName.getText()+"!");
							
							uName.setVisible(false);
							pWord.setVisible(false);
							pWordLabel.setVisible(false);
							loginButton.setVisible(false);
							registerButton.setVisible(false);
							
							userNameLogged.setText(uName.getText());
							userNameLogged.setVisible(true);
							
							frame.joinGame();
						}
					}
					catch (RemoteException e1)
					{
						e1.printStackTrace();
					}
				}
			}
		});

		add(loginButton);

		registerButton = new JButton("Register");
		registerButton.setOpaque(false);

		registerButton.addActionListener(new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				frame.showRegistrationPanel();
			}
		});

		add(registerButton);

	//	facade.getCommunicator().messageReceived.addListener(this);
	}

	@Override
	public void messageReceived(String senderId, NetworkMessage mess)
	{

		NetworkMessage message = mess.clone();
		MessageID id = message.getId(MessageID.class);

		switch (id)
		{
		case GAME_STARTED:
			// newGameButton.setEnabled(false);
			break;
		case GAME_FINISHED:
			// newGameButton.setEnabled(true);
			break;
		default:
			break;
		}
	}
}
